﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DDU.ViewModel;
using System.Windows.Threading;
using DDU.DataModel;

namespace DDU.Curriculum.Views
{
    public partial class BookGalleryView : PhoneApplicationPage
    {
        #region Contructors
        BookGalleryViewModel viewmodel;

        private DispatcherTimer playTimer;

        public BookGalleryView()
        {
            InitializeComponent();
            this.Loaded -= BookGalleryView_Loaded;
            this.Loaded += BookGalleryView_Loaded;

            this.playTimer = new DispatcherTimer();
            this.playTimer.Interval = TimeSpan.FromSeconds(2);
            this.playTimer.Tick += this.OnPlayTimerTick;
        } 
        #endregion

        #region Events
        private void OnPlayTimerTick(object sender, EventArgs e)
        {
            this.slideView.MoveToNextItem();
        }

        void BookGalleryView_Loaded(object sender, RoutedEventArgs e)
        {
            string guid = NavigationContext.QueryString["guid"];

            viewmodel = (BookGalleryViewModel)LayoutRoot.DataContext;
            viewmodel.Guid = guid;
            viewmodel.SlidePlayEvent += viewmodel_SlidePlayEvent;
        }

        void viewmodel_SlidePlayEvent(object sender, SlidePlayArgs e)
        {
            if (e.Playing)
            {
                playTimer.Start();

            }
            else
            {
                slideView.StopSlideShow();
                playTimer.Stop();
            }
        } 
        #endregion

        #region Override
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (viewmodel.SlideVisibility == System.Windows.Visibility.Visible)
            {
                viewmodel.StopCommand.Execute(null);
                e.Cancel = true;
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/BooksView.xaml", UriKind.RelativeOrAbsolute));
            }
            
        }
        #endregion

        private void GotoEditView(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/BookEditView.xaml?guid=" + (sender as Grid).Tag, UriKind.RelativeOrAbsolute));
        }
    }
}